<?php

namespace App\Http\Controllers\Backend;


use App\Enum\CodeEnum;
use App\Enum\EnterpriseCommuteEnum;
use App\Enum\OrderEnum;
use App\Enum\UserCardsEnum;
use App\Enum\WalletsEnum;
use App\Http\Controllers\Controller;
use App\Models\UserCardsModel;
use App\Models\UserEnterpriseModel;
use App\Services\BackendService;
use App\Services\EnterpriseCommuteService;
use App\Services\GeoService;
use App\Services\MapService;
use App\Services\OrderService;
use App\Services\VehicleConfigService;
use App\Services\WalletService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use League\CommonMark\Inline\Element\Code;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ApiController extends Controller
{
//    protected $zccClient = null;
    public function __construct()
    {
//        $this->zccClient =  new ZccmzjgyxmClient();
    }
    public function checkGpsPointAvail(Request $request){
        try{
            $result = GeoService::isPointsAvailable([$request->point], $request->city_code, $request->row_id);
            if( $result === true ) return success('此点可用。');
            else return fail(CodeEnum::ERROR, '此点不可用。');
        }catch (Exception $e){

            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 申请冻结用户的 公益诚信积分
     * @param Request $request
     * @return JsonResponse|null
     */
    public function advanceScoreApply(Request $request): ?JsonResponse
    {
        try {
            $result = BackendService::advanceScoreApply($request->phone, $request->score);
            if ( $result['code'] != CodeEnum::SUCCESS )
                return fail(CodeEnum::ERROR, $result['msg']);
            else return success($result['data']);
        } catch ( \Exception $e ){
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }


    /**
     * 创建企业租户
     * @param Request $request
     * @return JsonResponse|null
     * @throws Exception
     */
    public function createEnterpriseTenant(Request $request): ?JsonResponse
    {

        $params['name']         = $request->input('enterprise_name');
        $params['contactName']  = $request->input('contactor');
        $params['contactMobile']    = $request->input('contactor_phone');
        $params['website']      = $request->input('website');

        $params['password']     = EnterpriseCommuteEnum::TENANT_DEFAULT_PASSWORD;
        $params['username']     = EnterpriseCommuteEnum::TENANT_DEFAULT_ACCOUNT;
        $params['packageId']    = env('TENANT_PACKAGE_ID');
        $params['status']       = EnterpriseCommuteEnum::TENANT_STATUS_NORMAL;
        $params['expireTime']   = strtotime(EnterpriseCommuteEnum::TENANT_EXPIRE_TIME)*1000;
        $params['accountCount'] = EnterpriseCommuteEnum::TENANT_ACCOUNT_COUNT;


        try {
            $result = EnterpriseCommuteService::createEnterpriseTenant($params);
//            Log::notice($result);
            return success($result);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取企业员工的通勤积分
     * @param Request $request
     * @return JsonResponse|null
     */
    public function getEnterpriseClerkAxd(Request $request): ?JsonResponse
    {
        try {
            $result = EnterpriseCommuteService::getUserScore($request->input('user_phone'));
//            Log::notice($result);
            return success(['score'=>$result]);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 申请冻结 员工通勤积分
     *
     * @param Request $request
     * @return JsonResponse|null
     */
    public function applyFrozenUserCommuteAxd(Request $request): ?JsonResponse
    {
        try {
            $userPhone  = $request->input('user_phone');
            $amount     = $request->input('amount');
            $applyNo    = $request->input('apply_no');
            $memo       = $request->input('memo');
            $userId     = $request->input('user_id');
            $amountType = $request->input('amount_type');

            if($request->input('amount_type') != WalletsEnum::WALLET_MONEY_TYPE_COMMUTE_10W)
                throw new Exception("支付类型有误!");

            $result = EnterpriseCommuteService::applyFrozenOrder($userPhone, $applyNo, $amount, $memo);
            // 添加日志
            WalletService::addDeductFrozenBalanceLog([
                'order_no' => $applyNo,
                'user_id' => $userId,
                'amount' => $amount,
                'amount_type'=> $amountType,
                'comment' => $memo
            ]);
//            Log::notice($result);
            return success(['advanceNo'=>$result]);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 取消冻结 员工通勤积分
     *
     * @param Request $request
     * @return JsonResponse|null
     */
    public function cancelFrozenUserCommuteAxd(Request $request): ?JsonResponse
    {
        try {
            $userPhone  = $request->input('user_phone');
            $amount     = $request->input('amount');
            $orderNo    = $request->input('apply_no');
            $memo       = $request->input('memo');
            $userId     = $request->input('user_id');
            $amountType = $request->input('amount_type');


            $result = EnterpriseCommuteService::cancelFrozenOrder($userPhone, $orderNo, $amount);
            // 添加日志
            WalletService::addPaybackFrozenBalanceLog([
                'order_no' => $orderNo,
                'user_id' => $userId,
                'amount' => $amount,
                'amount_type'=> $amountType,
                'comment' => $memo
            ]);
//            Log::notice($result);
            return success(['advanceNo'=>$result]);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 申请冻结 出行积分
     *
     * @param Request $request
     * @return JsonResponse|null
     */
    public function applyFrozenUserGycxAxd(Request $request)
    {
        try {
            $userId     = $request->input('user_id');
            $amount     = $request->input('amount');
            $applyNo    = $request->input('apply_no');
            $amountType = $request->input('amount_type');
            $memo       = $request->input('memo');

            if( $amountType != WalletsEnum::WALLET_MONEY_TYPE_GYCX_AXD)
                throw new Exception("支付类型有误!");

            $id = WalletService::deductFrozenGycxAxd($userId, $applyNo, $amountType, $amount, $memo);
//            Log::notice($result);
            return success(['advanceNo'=>$id]);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 取消冻结 出行积分
     *
     * @param Request $request
     * @return JsonResponse|null
     */
    public function cancelFrozenUserGycxAxd(Request $request): ?JsonResponse
    {
        try {
            $userId     = $request->input('user_id');
            $amount     = $request->input('amount');
            $applyNo    = $request->input('apply_no');
            $amountType = $request->input('amount_type');
            $memo       = $request->input('memo');

            if( $amountType != WalletsEnum::WALLET_MONEY_TYPE_GYCX_AXD)
                throw new Exception("支付类型有误!");

            $id = WalletService::paybackFrozenGycxAxd($userId, $applyNo, $amountType, $amount, $memo);
//            Log::notice($result);
            return success(['advanceNo'=>$id]);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 该接⼝将⽤于将冻结的积分进⾏实际扣除。
     * @param Request $request
     * @return JsonResponse
     * {"code":200,"message":"success","data":[]}
     */
    public function advanceScoreSuccess(Request $request): JsonResponse
    {
        try {
            $result = BackendService::advanceScoreSuccess($request->advanceNo, $request->score);
            if ( $result['code'] != CodeEnum::SUCCESS )
                return fail(CodeEnum::ERROR, $result['msg']);
            else return success($result['data']);
        } catch ( \Exception $e ){
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }
    /**
     * 该接⼝将预付申请进⾏取消，返还⽤⼾剩余积分。
     * QUINB8VZIU3O4CVRNQDBVUJWTONBG2T38VDCOU3M
     * @param Request $request
     * @return JsonResponse
     * {"code":200,"message":"success","data":{"msg":"授权码不存在","code":400,"data":null}}
     * {"code":200,"message":"success","data":[]}
     */
    public function advanceScoreCancel(Request $request): JsonResponse
    {
        try {
            $result = BackendService::advanceScoreCancel($request->advanceNo);
            if ( $result['code'] != CodeEnum::SUCCESS )
                return fail(CodeEnum::ERROR, $result['msg']);
            else return success($result['data']);
        } catch ( \Exception $e ){
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }
    public function getUserScore(Request $request): JsonResponse
    {
        try {
            $result = BackendService::getUserScore($request->phone);
            if ( $result['code'] != CodeEnum::SUCCESS )
                return fail(CodeEnum::ERROR, $result['msg']);
            else return success($result['data']);
        } catch ( \Exception $e ){
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 给企业用户增加 积分
     * @param Request $request
     * @return JsonResponse
     */
    public function incrTenantAxd(Request $request): JsonResponse
    {
        try {
            $userCard = UserCardsModel::query()->find($request->input('user_card_id'));
            // 卡片 状态 异常，抛出
            if( $userCard->value_dispatch_status == UserCardsEnum::VALUE_DISPATCH_STATUS_DONE
            || $userCard->value_dispatch_status != UserCardsEnum::VALUE_DISPATCH_STATUS_TODO
            ){
                throw new Exception("用户购卡状态异常");
            }
            $enterprise = UserEnterpriseModel::query()->where(['user_id'=>$userCard->user_id])->first();
            if( empty($enterprise) || empty($enterprise->tenant_id)){
                throw new Exception("无法获取用户的企业开通信息。");
            }
            $result = EnterpriseCommuteService::incrTenantAxd($enterprise->tenant_id, $userCard->value_sxcx);
            if ( empty($result)  || !empty($result['code']) )
                throw new Exception("调用企业通勤接口返回异常".var_export($result,true));
            else return success($result);
        } catch ( \Exception $e ){
            Log::error("企业用户充值积分失败USER_CARD_ID=$userCard->id".$e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取地址解析的结果
     *
     * @param Request $request
     * @return JsonResponse|null
     */
    public function getAddressMapAnalyse(Request $request): ?JsonResponse
    {
        try {
            if( empty($request->address) ){
                throw new Exception("参数address为空");
            }

            $result = MapService::addressAnalyse($request->address, $request->region);
            return  success($result);
        }catch (Exception $e) {
            return fail( CodeEnum::BUSINESS_ERROR, $e->getMessage());
        }
    }
    public function getDistanceBetweenLocations(Request $request): ?JsonResponse
    {
        try {

            if( empty($request->locationFrom) ){
                throw new Exception("参数locationFrom为空");
            }
            if( empty($request->locationTo) ){
                throw new Exception("参数locationTo为空");
            }
            $result = MapService::distanceBetweenLocations($request->locationFrom, $request->locationTo);
//            Log::error(var_export($result,true));
            return  success($result);
        }catch (Exception $e) {
            return fail( CodeEnum::BUSINESS_ERROR, $e->getMessage());
        }
    }

}
